package svc

import (
	"github.com/olivere/elastic/v7"
	"github.com/renxingcode/esign-go-sdk"
	eSignConfig "github.com/renxingcode/esign-go-sdk/config"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"gozero-demo/internal/config"
	"gozero-demo/internal/model/dao/query"
	"log"
	"os"
	"time"
)

type ServiceContext struct {
	Config   config.Config
	DB       *gorm.DB     //gorm的db对象
	Model    *query.Query //gorm的gen的query对象
	ES       *elastic.Client
	ESignSdk *esign.Client // e签宝的sdk对象
}

func NewServiceContext(c config.Config) *ServiceContext {
	//initCtx := context.Background()

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: 10 * time.Second, // 慢SQL阈值,默认10秒钟
			LogLevel:      logger.Silent,    // 日志级别 Silent：静默级别,Error：错误级别,Warn：警告级别,Info：信息级别
			Colorful:      true,             // 是否彩色打印
		},
	)
	db, _ := gorm.Open(mysql.Open(c.Mysql.DataSource), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "",   // 表名前缀
			SingularTable: true, // 使用单数表名，启用该选项，会区分 user 和 users 表为两个不同的数据表
		},
	})

	/*
		// 初始化 Elasticsearch 客户端单例实例
		esCfg := es.LoadESConfig(c)
		//esClient, err := es.GetESClient(esCfg)
		esClient, err := es.GetESClient(initCtx, esCfg)
		if err != nil {
			logx.Errorf("failed to get Elasticsearch client: %v", err)
		}
	*/

	//初始化e签宝客户端
	esignSdkConfig, err := eSignConfig.NewConfig(c.ESign.AppId, c.ESign.AppSecret, c.ESign.BaseUrl, c.ESign.OrgID, c.ESign.GrantType, c.ESign.IsWriteLog)
	if err != nil {
		logx.Errorf("Failed to init eSignSdk, err: %v", err)
	}
	esignSdk := esign.NewClient(esignSdkConfig)

	return &ServiceContext{
		Config: c,
		DB:     db,
		Model:  query.Use(db),
		//ES:     esClient,
		ESignSdk: esignSdk,
	}
}
